﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;
using Avivo.Tools.Sprite.Models;
using Microsoft.Win32;

namespace Avivo.Tools.Sprite
{
	public class LoadXmlCommand : ICommand
	{
		#region Private members
		private SpriteViewModel parent;
		#endregion

		#region Constructor
		public LoadXmlCommand(SpriteViewModel parent)
		{
			this.parent = parent;
		}
		#endregion

		#region ICommand Members
		public bool CanExecute(object parameter)
		{
			return true;
		}

		public event EventHandler CanExecuteChanged;

		public void Execute(object parameter)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.DefaultExt = "*.xml";
			dialog.Filter = "Sprite data (*.xml)|*.xml";

			if (dialog.ShowDialog() == true)
			{
				LoadXml(dialog.FileName, this.parent);
			}
		}
		#endregion

		#region Protected methods
		protected void LoadXml(string path, SpriteViewModel model)
		{
			try
			{
				var doc = XDocument.Load(path);
				if (doc.Root.Name == "Sprites")
				{
					foreach (var group in doc.Root.Elements("Group"))
					{
						model.BaseClassName = group.Attribute("Name").Value;
						model.InputDirectory = group.Attribute("InputDirectory").Value;
						model.OutputDirectory = group.Attribute("OutputDirectory").Value;
						model.BuildSampleHtml = bool.Parse(group.Attribute("BuildHtml").Value);
						model.EnableCss = bool.Parse(group.Attribute("BuildCss").Value);
						model.Sprites.Clear();

						foreach (var item in group.Elements("Item"))
						{
							SpriteModel sprite = new SpriteModel();
							sprite.Name = item.Attribute("Name").Value;
							sprite.Content = item.Attribute("Content").Value;
							sprite.Template = item.Attribute("Template").Value;
							model.Sprites.Add(sprite);
						}

						break; //Only one group should be parsed
					}
				}
				else
				{
					MessageBox.Show("Expecting 'Sprites' for root tag name.");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
			}
		}
		#endregion
	}
}
